<template>

  <tracking-cam
    ref="cam"
    :tracking="true"
    :track-capture="false"
    :show-track-tips="false"
    @face-out="faceOut"
    @started="startTimer"
    @capture="saveCapture"/>

</template>

<script>
import { saveCapture } from '@/api/paper/capture'
import TrackingCam from '@/components/TrackingCam/index.vue'

export default {
  name: 'ExamCam',
  components: {
    TrackingCam
  },
  props: {
    camOn: Boolean,
    camInterval: Number,
    paperId: String
  },
  data() {
    return {
      // 文件上传参数
      dataObj: {},
      // 定时截图参数
      timer: null,
      intervalSec: 9999
    }
  },

  watch: {
    camOn: {
      handler() {
        this.fill()
      }
    }
  },

  destroyed() {
    if (this.timer != null) {
      clearInterval(this.timer)
    }
  },

  created() {
    // 操作检测
    this.fill()
  },

  methods: {

    fill() {
      // 操作检测
      if (this.camOn && this.camInterval > 0) {
        this.intervalSec = this.camInterval * 60000
      }
    },

    // 开启定时截屏
    startTimer() {
      if (this.timer != null) {
        clearInterval(this.timer)
      }

      this.timer = setInterval(() => {
        // 定时进行截图
        this.$refs.cam.capture()
      }, this.intervalSec)
    },

    // 保存截图
    saveCapture(base64) {
      // 保存数据
      const data = { paperId: this.paperId, base64: base64 }
      saveCapture(data).then(res => {
        console.log('++++++++++ capture saved', res)
        const data = res.data

        // 达到上限
        if (data.isBreak) {
          this.$emit('break', `连续${data.failCount}次人脸识别失败，系统强制交卷！`)
          return
        }

        // 还有机会
        if (data.failCount > 0) {
          this.$message.error(`人脸识别已失败${data.failCount}次，连续失败${data.faceChance}次将自动交卷！`)
        }
      })
    },

    faceOut() {
      this.$message.error(`请诚信考试，确保人脸在摄像头中央！`)
    }

  }
}
</script>

